package com.taxshare.seller.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taxshare.mybatis.pager.PageHelp;
import com.taxshare.mybatis.pager.PageRequest;
import com.taxshare.response.beans.Response;
import com.taxshare.seller.entity.FphmdDetailEntity;
import com.taxshare.seller.entity.FphmdEntity;
import com.taxshare.seller.entity.SellerInvoiceEntity;
import com.taxshare.seller.mapper.FphmdDetailMapper;
import com.taxshare.seller.mapper.FphmdMapper;
import com.taxshare.seller.mapper.InvoicedMapper;
import com.taxshare.seller.util.LqHttpUtil;
import com.taxshare.seller.view.dto.FphmdDTO;
import com.taxshare.seller.view.vo.FphmdVO;
import com.taxshare.tools.util.UUIDUitl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: FphmdService
 * @Description:
 * @author: lpp
 * @date: 2024/10/21 10:37
 */
@Slf4j
@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public class FphmdService extends ServiceImpl<FphmdMapper, FphmdEntity> {

    @Value("${lqpt.ptbh}")
    private String ptbh;
    @Value("${lqpt.hexKey}")
    private String hexKey;
    @Value("${lqpt.url}")
    private String url;
    @Value("${lqpt.ip}")
    private String ip;
    @Value("${lqpt.macdz}")
    private String macdz;


    @Value("${empower.url}")
    private String empowerUrl;

    @Autowired
    FphmdDetailMapper fphmdDetailMapper;

    @Autowired
    InvoicedMapper invoicedMapper;
    @Autowired
    LqHttpUtil lqHttpUtil;

    /**
     * 查询发票号码段
     *
     * @param fphmdDTO
     * @return
     */
    public Response query(PageRequest<FphmdDTO> fphmdDTO) {
        QueryWrapper<FphmdEntity> queryWrapper = new QueryWrapper();
        FphmdDTO fphmdInfo = fphmdDTO.getInfo();
        if (!StrUtil.hasBlank(fphmdInfo.getNsrsbh())) {
            queryWrapper.eq("nsrsbh", fphmdInfo.getNsrsbh());
        }
        if (!StrUtil.hasBlank(fphmdInfo.getLysl())) {
            queryWrapper.eq("lysl", fphmdInfo.getLysl());
        }
        queryWrapper.orderByDesc("create_time");
        IPage<FphmdVO> result = PageHelp.siamplePage(this, queryWrapper, fphmdDTO.getPage(), FphmdVO.class);
        return Response.success(result);
    }

    /**
     *获取数字化电子发票批量预赋码信息
     * @return
     */
    public Map<String,Object> tbFphmd(Map<String, Object> param) {
        String lysl = String.valueOf(param.get("lysl"));
        String nsrsbh = "91140000731914164T";
        Map<String,Object> resultMap = new HashMap();
        log.info("========获取数字化电子发票批量预赋码信息========开始======");
        JSONObject reqJson = new JSONObject();
        reqJson.put("nsrsbh",nsrsbh);
        reqJson.put("lysl",lysl);
        reqJson.put("ywlsh",ptbh+ptbh+ UUIDUitl.UUID32());//流水号
        String reqStr = reqJson.toJSONString();
        log.info("========入参======>>>"+reqStr);
        try{
            url = url+"202007/QDFPPLFM";
            JSONObject result_json = lqHttpUtil.sendPostLq(reqStr,url);
            String returncode = result_json.getString("returncode");
            if("00".equals(returncode)) {
                String fpqshm = result_json.getString("fpqshm");
                String fpzzhm = result_json.getString("fpzzhm");
                String lysl1 = result_json.getString("lysl");
                FphmdEntity fphmd = new FphmdEntity();
                String zbid = UUIDUitl.UUID32();
                fphmd.setUuid(zbid);
                fphmd.setFpqshm(fpqshm);
                fphmd.setFpzzhm(fpzzhm);
                fphmd.setLysl(lysl1);
                fphmd.setNsrsbh(nsrsbh);
                baseMapper.insert(fphmd);
                BigInteger fpqshmB = new BigInteger(fpqshm);
                BigInteger fpzzhmB = new BigInteger(fpzzhm);
                for (int i = 0; i <= Integer.valueOf(fpzzhmB.subtract(fpqshmB).toString()); i++) {
                    FphmdDetailEntity fphmdDetail = new FphmdDetailEntity();
                    fphmdDetail.setUuid(UUIDUitl.UUID32());
                    fphmdDetail.setFphmId(zbid);
                    fphmdDetail.setFphm(String.valueOf(fpqshmB.add(new BigInteger(String.valueOf(i)))));
                    fphmdDetail.setNsrsbh(nsrsbh);
                    fphmdDetail.setStatus("0");
                    fphmdDetailMapper.insert(fphmdDetail);
                }
                resultMap.put("code", "0000");
                resultMap.put("msg", "同步成功");
            }
        }catch (Exception e){
            log.error("获取数字化电子发票批量预赋码信息,异常：",e);
            e.printStackTrace();
            resultMap.put("code","9999");
            resultMap.put("msg",e);
        }

        log.info("========获取数字化电子发票批量预赋码信息========结束======");
        return resultMap;
    }


    /**
     *上传发票汇总确认信息
     * @param param
     * @return
     */
    public Map SCFPHZQRXX(Map<String, Object> param)  {
        String yf = String.valueOf(param.get("yf"));
        String sellerTaxNo = String.valueOf(param.get("sellerTaxNo"));
        log.info("========上传发票汇总确认信息========开始======");
        Map<String, Object> resultMap = new HashMap();
        Map<String, Object> param01 = new HashMap<>();
        param01.put("invoiceDate",yf);
        param01.put("makeInvoiceState","2");
        param01.put("sellerTaxNo",sellerTaxNo);
        param01.put("makeInvoiceType","0");//蓝票
        List<SellerInvoiceEntity> kpzbList = invoicedMapper.selectSCFPHZQRXX(param01);
        param01.put("makeInvoiceType","1");//红票
        List<SellerInvoiceEntity> kpzbList01 = invoicedMapper.selectSCFPHZQRXX(param01);
        try{
            if(kpzbList!=null && kpzbList.size()!=0) {
                url = url + "202007/SCFPHZQRXX";
                SellerInvoiceEntity kpzb01 = kpzbList.get(0);
                SellerInvoiceEntity kpzb02 = kpzbList01.get(0);
                JSONObject reqJson = new JSONObject();
                reqJson.put("xsfnsrsbh", sellerTaxNo);//销售方纳税人识别号
                reqJson.put("xsfsjswjgdm", "11400");//销售方省级税务机关代码
                reqJson.put("ywlx", "0");//业务类型0：确认1：取消
                reqJson.put("ptbh", ptbh);//平台编号
                reqJson.put("yf", yf);//格 式 ：yyyy-MM
                reqJson.put("lzfpsl", kpzb01.getRemark());//蓝字发票数量
                reqJson.put("lzfpje", kpzb01.getTotalSumTax());//蓝字发票金额
                reqJson.put("lzfpse", kpzb01.getTotalTax());//蓝字发票税额
                reqJson.put("hzfpsl", kpzb02.getRemark());//红字发票数量
                reqJson.put("hzfpje", kpzb02.getTotalSumTax());//红字发票金额
                reqJson.put("hzfpse", kpzb02.getTotalTax());//红字发票税额
                String reqStr = reqJson.toJSONString();
                log.info("========入参======>>>" + reqStr);
                JSONObject result_json = lqHttpUtil.sendPostLq(reqStr,url);
                String returncode = result_json.getString("returncode");
                if("00".equals(returncode)) {
                    resultMap.put("code", "0000");
                    resultMap.put("msg", "成功");
                }
            }
        }catch (Exception e){
            log.error("上传发票汇总确认信息,异常：",e);
            resultMap.put("code","9999");
            resultMap.put("msg",e);
            e.printStackTrace();
        }
        log.info("========上传发票汇总确认信息========结束======");
        return resultMap;
    }

    /**
     * 查询发票汇总确认信息
     * @param param
     * @return
     */
    public Map CXFPHZQRXX(Map<String, Object> param)  {
        String yf = String.valueOf(param.get("yf"));
        String sellerTaxNo = String.valueOf(param.get("sellerTaxNo"));
        log.info("========查询发票汇总确认信息========开始======");
        Map<String, Object> resultMap = new HashMap();
        try{
            url = url + "202007/CXFPHZQRXX";
            JSONObject reqJson = new JSONObject();
            reqJson.put("xsfnsrsbh",sellerTaxNo);//销售方纳税人识别号
            reqJson.put("xsfsjswjgdm","11400");//销售方省级税务机关代码
            reqJson.put("ptbh",ptbh);//平台编号
            reqJson.put("yf",yf);//格 式 ：yyyy-MM
            String reqStr = reqJson.toJSONString();
            log.info("========入参======>>>" + reqStr);

            JSONObject result_json = lqHttpUtil.sendPostLq(reqStr,url);
            String returncode = result_json.getString("returncode");
            if("00".equals(returncode)) {
                JSONArray fphzqrxxList = result_json.getJSONArray("fphzqrxxList");
                resultMap.put("code", "0000");
                resultMap.put("msg", fphzqrxxList.toJSONString());
            }
        }catch (Exception e){
            log.error("上传发票汇总确认信息,异常：",e);
            resultMap.put("code","9999");
            resultMap.put("msg",e);
            e.printStackTrace();
        }
        log.info("========上传发票汇总确认信息========结束======");
        return resultMap;
    }
}


